package com.beaven.model.data.message;

import android.text.TextUtils;
import com.beaven.model.data.helper.DbHelper;
import com.beaven.model.data.helper.GroupHelper;
import com.beaven.model.data.helper.MessageHelper;
import com.beaven.model.data.helper.UserHelper;
import com.beaven.model.data.user.UserDispatcher;
import com.beaven.model.model.card.MessageCard;
import com.beaven.model.model.db.Group;
import com.beaven.model.model.db.Message;
import com.beaven.model.model.db.User;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;
import timber.log.Timber;

/**
 * author: Beaven
 * time: 2017/6/1 11:06
 */

public class MessageDispatcher implements MessageCenter {

  private static volatile MessageDispatcher dispatcher;

  public static MessageDispatcher getInstance() {
    if (dispatcher == null) {
      synchronized (UserDispatcher.class) {
        if (dispatcher == null) {
          dispatcher = new MessageDispatcher();
        }
      }
    }
    return dispatcher;
  }

  private MessageDispatcher() {
  }

  private List<Message> messages;

  @Override public void dispatch(MessageCard... cards) {
    messages = new ArrayList<>();
    Observable.from(cards).subscribeOn(Schedulers.io()).subscribe(new Subscriber<MessageCard>() {
      @Override public void onCompleted() {
        if (messages.size() > 0) {
          DbHelper.instance().saveModel(Message.class, messages.toArray(new Message[0]));
        }
      }

      @Override public void onError(Throwable e) {
        Timber.e(e);
      }

      @Override public void onNext(MessageCard messageCard) {
        Timber.i("消息处理---" + messageCard);
        if (messageCard == null
            || TextUtils.isEmpty(messageCard.getSenderId())
            || TextUtils.isEmpty(messageCard.getId())
            || (TextUtils.isEmpty(messageCard.getReceiverId()) && TextUtils.isEmpty(
            messageCard.getGroupId()))) {
          return;
        }

        Message message = MessageHelper.findFromLocal(messageCard.getId());
        if (message != null) {

          // 如果本地消息显示已经完成则不做处理
          if (message.getStatus() == Message.STATUS_DONE) return;

          // 新状态为完成才更新服务器时间，不然不做更新
          if (messageCard.getStatus() == Message.STATUS_DONE) {
            // 网络发送成功，修改时间为服务器的时间
            message.setCreateAt(messageCard.getCreateAt());
          }

          // 更新一些会变化的内容
          message.setContent(messageCard.getContent());
          // 更新状态
          message.setStatus(messageCard.getStatus());
        } else {
          // 没找到本地消息，初次在数据库存储
          User sender = UserHelper.findById(messageCard.getSenderId());
          User receiver = null;
          Group group = null;
          if (!TextUtils.isEmpty(messageCard.getReceiverId())) {
            receiver = UserHelper.findById(messageCard.getReceiverId());
          } else if (!TextUtils.isEmpty(messageCard.getGroupId())) {
            group = GroupHelper.findFromLocal(messageCard.getGroupId());
          }

          if (receiver == null && group == null && sender != null) return;

          message = messageCard.build(sender, receiver, group);
        }
        messages.add(message);
      }
    });
  }
}
